//
//  ZXJInputVerityCodeViewController.m
//  academic_records
//
//  Created by zhang bozhao on 2020/8/5.
//  Copyright © 2020 zhang bozhao. All rights reserved.
//

#import "ZXJInputVerityCodeViewController.h"
#import "ZXJSettingNewPWViewController.h"
#import "LoginRequest.h"
#import "ZXJHomePageViewController.h"
#import "AcademicTabbarViewController.h"
#import "LoginRequest.h"

@interface ZXJInputVerityCodeViewController ()
@property (weak, nonatomic) IBOutlet UILabel *phoneLab;
@property (weak, nonatomic) IBOutlet UIButton *tipsBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UILabel *firstLab;
@property (weak, nonatomic) IBOutlet UILabel *secondLab;
@property (weak, nonatomic) IBOutlet UILabel *thirdLab;
@property (weak, nonatomic) IBOutlet UILabel *fourthLab;
@property (weak, nonatomic) IBOutlet UILabel *fifthLab;
@property (weak, nonatomic) IBOutlet UILabel *sixLab;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topHeight;
@property (nonatomic, strong)NSString *codeString;
@property (nonatomic, strong)NSArray<UILabel *>*labelArray;
@property (nonatomic,strong) UITextField *textField;
@property (nonatomic, assign)BOOL isRequst;
@property(strong,nonatomic) NSTimer *timer;
@property(nonatomic,strong)WKWebViewController *webView;
@end

@implementation ZXJInputVerityCodeViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController.navigationBar setHidden:YES];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.webView = [[WKWebViewController alloc]init];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    self.topHeight.constant = k_Height_StatusBar+(NavBar_H-k_Height_StatusBar-30)/2;
}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.nextBtn.layer.cornerRadius = 22.0f;
    [PPViewTool setGradualChangingColor:self.nextBtn];
    if (self.type == 2) {
        self.nextBtn.hidden = YES;
    }else{
        self.nextBtn.hidden = NO;
    }
    self.phoneLab.text = self.phone;
    self.labelArray = [NSArray arrayWithObjects:self.firstLab,self.secondLab,self.thirdLab,self.fourthLab,self.fifthLab,self.sixLab, nil];
    _textField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMinX(self.firstLab.frame),CGRectGetMinY(self.firstLab.frame) , 300, 50)];
    _textField.textColor = [UIColor clearColor];
    [_textField setTintColor:[UIColor clearColor]];
    [self.view addSubview:_textField];
    [_textField becomeFirstResponder];
    _textField.keyboardType = UIKeyboardTypeNumberPad;
    [_textField addTarget:self action:@selector(textDidChanged:) forControlEvents:(UIControlEventEditingChanged)];
    self.codeString = @"";
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:_tipsBtn.titleLabel.text];
    [str addAttribute:NSForegroundColorAttributeName value:HexRGB(0xE6554F) range:NSMakeRange(0, 3)];
    [_tipsBtn setAttributedTitle:str forState:(UIControlStateNormal)];
    [self timeBegain];
}
- (void)timeBegain
{
    // 加1个定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeUp) userInfo: nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}
-(void)timeUp
{
    NSAttributedString * title = _tipsBtn.titleLabel.attributedText;
    NSInteger time = [[title.string substringWithRange:NSMakeRange(0, title.length - 4)] integerValue];
    if (time >1) {
       time--;
       [_tipsBtn setTitle:[NSString stringWithFormat:@"%ldS后重发",time] forState:(UIControlStateNormal)];
       NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%ldS后重发",time]];
       [str addAttribute:NSForegroundColorAttributeName value:HexRGB(0xE6554F) range:NSMakeRange(0, title.length-3)];
       [_tipsBtn setAttributedTitle:str forState:(UIControlStateNormal)];
        _tipsBtn.userInteractionEnabled = NO;
    }else{
        NSString *string = @"重新获取";
       NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string];
       [str addAttribute:NSForegroundColorAttributeName value:HexRGB(0xE6554F) range:NSMakeRange(0, string.length)];
       [_tipsBtn setAttributedTitle:str forState:(UIControlStateNormal)];
        _tipsBtn.userInteractionEnabled = YES;
    }
}
-(void)clickToEditTextField
{
    [_textField becomeFirstResponder];
}
- (void)textDidChanged:(UITextField *)textField {
    
    
    if (textField.text.length <= 6) {
        
        for (int i = 0; i < textField.text.length; i ++) {
            UILabel *label = self.labelArray[i];
            label.text = [textField.text substringWithRange:NSMakeRange(i, 1)];
//            if (textField.text.length == 6) {
//               _codeString = [_codeString stringByAppendingString:label.text];
//            }
        }
        for (int i = 0; i < self.labelArray.count; i++) {
            if (i >= textField.text.length) {
                UILabel *lab = self.labelArray[i];
                lab.text = @"";
            }
        }
    }
    NSLog(@"%ld",_codeString.length);
    if (textField.text.length == 6 &&![textField.text isEqualToString:_codeStr]) {
        [XWHUDManager showCustomImageHUD:[UIImage imageNamed:FailedImg] message:@"验证码输入错误" timer:2];
    }
    if (self.type != 3) {
        if ([textField.text isEqualToString:_codeStr]) {
            if ([self.codeMode isEqual:@"3"]) {
                [self bindingPhone];
            }else{
                [self requestData];
            }
        }
    }else{
        self.codeString = textField.text;
    }

}

-(void)requestData
{
      NSMutableDictionary *dict = [NSMutableDictionary dictionary];
      [dict setObject:self.textField.text  forKey:@"code"];
      [dict setObject:[[NSUserDefaults standardUserDefaults]objectForKey:@"PHONENUM"] forKey:@"mobile"];
      [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"IPhoneUUID"] forKey:@"sessionID"];
      [LoginRequest  do_lgoinByVerityCode:dict :^(id  _Nullable data, ResultCode resultCode, NSError * _Nullable Error) {
         if (resultCode == SucceedCode) {
             [[NSUserDefaults standardUserDefaults]setObject:[data objectForKey:@"uGuid"] forKey:@"USERID"];
             [[NSUserDefaults standardUserDefaults]setObject:@(YES) forKey:@"IS_LOGIN"];
             [[NSUserDefaults standardUserDefaults]setObject:[NSMutableArray array] forKey:HistoryArr];
             AcademicTabbarViewController *minenav = [[AcademicTabbarViewController alloc]init];
             APP_DELEGATE.window.rootViewController=minenav;
         }else{
             [XWHUDManager showTipHUD:[data objectForKey:@"message"]];
         }
      }];
    
}
-(void)bindingPhone
{
     NSMutableDictionary *params = [NSMutableDictionary dictionary];
     [params setValue:[[NSUserDefaults standardUserDefaults]objectForKey:@"UNIONID"] forKey:@"unionid"];
     [params setValue:self.phoneLab.text forKey:@"mobile"];
     [params setValue:self.codeStr forKey:@"code"];
     [params setValue:@"4"  forKey:@"source"];
     [params setValue:[[NSUserDefaults standardUserDefaults] objectForKey:@"IPhoneUUID"] forKey:@"sessionID"];
     [LoginRequest User_bindphone:params :^(id  _Nullable data, ResultCode resultCode, NSError * _Nullable Error) {
         if (resultCode == SucceedCode) {
             NSDictionary *dict = data[@"data"];
             NSString *userid = [NSString stringWithFormat:@"%@",[dict objectForKey:@"uGuid"]];
             [[NSUserDefaults standardUserDefaults]setObject:userid forKey:@"USERID"];
             [[NSUserDefaults standardUserDefaults]setObject:@(YES) forKey:@"IS_LOGIN"];
             [[NSUserDefaults standardUserDefaults]setObject:@"已绑定" forKey:@"BindingWeChat"];
             [[NSUserDefaults standardUserDefaults]setObject:self.phoneLab.text forKey:@"PHONENUM"];
             [[NSUserDefaults standardUserDefaults]setObject:[NSMutableArray array] forKey:HistoryArr];
             AcademicTabbarViewController *minenav = [[AcademicTabbarViewController alloc]init];
             APP_DELEGATE.window.rootViewController=minenav;
         }else{
             [XWHUDManager showTipHUD:[data objectForKey:@"message"]];
         }
     }];
}
- (IBAction)sendVerityCodeAction:(id)sender {
    MJWeakSelf
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:self.phone forKey:@"phone"];
    [params setObject:self.codeMode forKey:@"codeMode"];
    [LoginRequest getpwd_vercode:params :^(id  _Nullable data, ResultCode resultCode, NSError * _Nullable Error) {
         if (resultCode == SucceedCode) {
         [weakSelf.tipsBtn setTitle:@"60S后获取" forState:(UIControlStateNormal)];
         NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:weakSelf.tipsBtn.titleLabel.text];
         [str addAttribute:NSForegroundColorAttributeName value:HexRGB(0xE6554F) range:NSMakeRange(0, 3)];
         [weakSelf.tipsBtn setAttributedTitle:str forState:(UIControlStateNormal)];
         [weakSelf timeBegain];
         }
    }];
    
}
- (IBAction)nextAction:(id)sender {
    if ([self.codeString isEqualToString:self.codeStr]) {
        ZXJSettingNewPWViewController *settingPWVC = [[ZXJSettingNewPWViewController alloc]init];
        settingPWVC.verityCode = self.codeStr;
        [self.navigationController pushViewController:settingPWVC animated:YES];
    }else{
        [XWHUDManager showTipHUD:@"请输入正确的验证码"];
    }
}
- (IBAction)userAgreementAction:(id)sender {
    self.webView.titleStr = @"用户协议";
    self.webView.webUrl = @"http://app.zhishen.net.cn/xsz_h5/AppHtml/App_ServiceUsage.html";
   [self.navigationController pushViewController:self.webView animated:YES];
}
- (IBAction)securityAction:(id)sender {
    self.webView.titleStr = @"隐私协议";
    self.webView.webUrl = @"http://app.zhishen.net.cn/xsz_h5/AppHtml/App_Privacy.html";
   [self.navigationController pushViewController:self.webView animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
